package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import dao.MemTypeDao;
import entity.MemType;
import util.DBUtils;

public class MemTypeDaoImpl implements MemTypeDao {

	@Override
	public boolean insert(MemType type)  {
		try (Connection c = DBUtils.getConnection();){
			String sql = "insert into mem_type(type_name,create_time) values(?,now())";
			PreparedStatement ps = c.prepareStatement(sql);
			ps.setString(1, type.getTypeName());
			int row = ps.executeUpdate();
			return row == 1? true : false;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	public List<MemType> selectAll() {
		try (Connection c = DBUtils.getConnection();){
			String sql = "select type_id,type_name,create_time,modify_time from mem_type where delete_flag=0";
			PreparedStatement ps = c.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			List<MemType> typeList = new ArrayList<>();
			while (rs.next()) {
				MemType mt = new MemType();
				mt.setTypeId(rs.getInt(1));
				mt.setTypeName(rs.getString(2));
				mt.setCreateTime(rs.getTimestamp(3));
				mt.setModifyTime(rs.getTimestamp(4));
				typeList.add(mt);
			}
			return typeList.isEmpty() ? Collections.emptyList() : typeList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
}
